#pragma once

#include <iostream>
#include <functional>
#include <unordered_map>
#include "Log.hpp"
#include "Sock.hpp"
#include "Err.hpp"
#include "Epoller.hpp"
#include "Util.hpp"
#include "Protocol.hpp"

namespace tcpserver
{
    class Connection;
    class TcpServer;

    static const uint16_t defaultport = 8080;
    static const int num = 64;

    using func_t = std::function<void(Connection *)>;
    // using handler_t = std::function<void(const std::string& package);

    class Connection
    {
    public:
        Connection(int sock, TcpServer *tsp)
            : _sock(sock), _tsp(tsp)
        {
        }

        void Register(func_t r, func_t s, func_t e)
        {
            _recver = r;
            _sender = s;
            _excepter = e;
        }

        ~Connection()
        {
        }

        void Close()
        {
            close(_sock);
        }

    public:
        int _sock;
        std::string _inbuffer;  // 读缓冲区
        std::string _outbuffer; // 发缓冲区

        func_t _recver;   // 从sock中读
        func_t _sender;   // 向sock中写
        func_t _excepter; // 处理sock IO的时候上面的异常事件

        TcpServer *_tsp; // 回调 

        uint64_t lasttime;
    };

    class TcpServer
    {
    private:
        void Recver(Connection *conn)
        {
            conn->lasttime = time(nullptr);
            char buffer[1024];
            while (true)
            {
                ssize_t s = recv(conn->_sock, buffer, sizeof(buffer) - 1, 0);
                if (s > 0)
                {
                    buffer[s] = 0;
                    conn->_inbuffer += buffer;
                    logMessage(DEBUG, "\n%s", conn->_inbuffer);
                    service(conn);
                }
                else if (s == 0)
                {
                    if (conn->_excepter)
                    {
                        conn->_excepter(conn);
                        return;
                    }
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                    {
                        break;
                    }
                    else if (errno == EINTR)
                    {
                        continue;
                    }
                    else
                    {
                        if (conn->_excepter)
                        {
                            conn->_excepter(conn);
                            return;
                        }
                    }
                }
            }
            // logMessage(DEBUG, "%d -> %s", conn->_sock, conn->_inbuffer.c_str());

            // 向上交付
        }

        void Sender(Connection *conn)
        {
            conn->lasttime = time(nullptr);
            while (true)
            {
                ssize_t s = send(conn->_sock, conn->_outbuffer.c_str(), conn->_outbuffer.size(), 0);
                if (s > 0)
                {
                    if (conn->_outbuffer.empty())
                    {
                        // EnableReadWrite(conn, true, false);
                        break;
                    }
                    else
                    {
                        conn->_outbuffer.erase(0, s);
                    }
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->_excepter)
                        {
                            conn->_excepter(conn);
                            return;
                        }
                    }
                }
            }
            // 如果没有发完，需要对对应的sock开启写事件关心，如果发完了，就要关闭
            if (!conn->_outbuffer.empty())
            {
                conn->_tsp->EnableReadWrite(conn, true, true);
            }
            else
                conn->_tsp->EnableReadWrite(conn, true, false);
        }

        void Excepter(Connection *conn)
        {
            logMessage(DEBUG, "Excepter begin");
            _epoller.Control(conn->_sock, 0, EPOLL_CTL_DEL);
            conn->Close();
            _connections.erase(conn->_sock);

            logMessage(DEBUG, "关闭%d 文件描述符的所有资源", conn->_sock);

            delete conn;
        }

        void Accepter(Connection *conn)
        {
            for (;;)
            {
                std::string clientip;
                uint16_t clientport;
                int err = 0;
                int sock = _sock.Accept(&clientip, &clientport, &err);
                if (sock > 0)
                {
                    AddConnection(
                        sock, EPOLLIN | EPOLLET,
                        std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                        std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                        std::bind(&TcpServer::Excepter, this, std::placeholders::_1));

                    logMessage(DEBUG, "get a new link, info: [%s:%d]", clientip.c_str(), clientport);
                }
                else
                {
                    if (err == EAGAIN || err == EWOULDBLOCK)
                    {
                        break;
                    }
                    else if (err = EINTR)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        void AddConnection(int sock, uint32_t events, func_t recver, func_t sender, func_t excepter)
        {
            // 1. 为sock创建Connection对象，并初始化添加到connections中
            if (events & EPOLLET)
                Util::SetNonBlock(sock);
            Connection *conn = new Connection(sock, this);

            // 2. 给对应的sock设置对应的回调处理方法
            conn->Register(recver, sender, excepter);

            // 3. 将sock和它关心的时间写道epoll中
            bool r = _epoller.AddEvent(sock, events);
            assert(r);
            (void)r;

            // 4. 将kv添加到connections中
            _connections.insert(std::make_pair(sock, conn));

            logMessage(DEBUG, "add new sock: %d in epoll and unordered_map", sock);
        }

        bool IsConnectionExits(int sock)
        {
            auto iter = _connections.find(sock);
            return iter != _connections.end();
        }

        void Loop(int timeout)
        {
            int n = _epoller.Wait(_revs, _num, timeout); // 获取已经就绪的事件
            for (int i = 0; i < n; ++i)
            {
                int sock = _revs[i].data.fd;
                uint32_t events = _revs[i].events;

                // 将所有的异常问题转化成为读写问题
                if (events & EPOLLERR)
                    events |= (EPOLLIN | EPOLLOUT);
                if (events & EPOLLHUP)
                    events |= (EPOLLIN | EPOLLOUT);

                // listen事件就绪 和 其它事件就绪都可以调用内置方法
                if ((events & EPOLLIN) && IsConnectionExits(sock) && _connections[sock]->_recver)
                {
                    _connections[sock]->_recver(_connections[sock]);
                }
                if ((events & EPOLLOUT) && IsConnectionExits(sock) && _connections[sock]->_sender)
                {
                    _connections[sock]->_sender(_connections[sock]);
                }
            }
        }

    public:
        TcpServer(func_t func, uint16_t port = defaultport)
            : _service(func), _port(port), _revs(nullptr)
        {
        }

        void InitServer()
        {
            // 1. 创建socket
            _sock.Socket();
            _sock.Bind(_port);
            _sock.Listen();

            // 2. 创建epoll模型
            _epoller.Create();

            // 3. 添加listensock到epoll中，需要将fd设为非阻塞
            // listensock也是一个socket，也要看作一个Connection对象
            AddConnection(_sock.Fd(), EPOLLIN | EPOLLET,
                          std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);

            _revs = new struct epoll_event[num];
            _num = num;
        }

        void EnableReadWrite(Connection *conn, bool readable, bool writeable)
        {
            uint32_t event = (readable ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0) | EPOLLET;
            _epoller.Control(conn->_sock, event, EPOLL_CTL_MOD);
        }

        // 事件派发
        void Dispatch()
        {
            int timeout = 1000;
            while (true)
            {
                Loop(timeout);
                // logMessage(DEBUG, "time out ...");

                // 遍历connections计算每一个链接的已经有多长时间没有动，实现资源的管理
            }
        }

        ~TcpServer()
        {
            _sock.Close();
            _epoller.Close();
            if (nullptr != _revs)
                delete[] _revs;
        }

    private:
        uint16_t _port;
        Sock _sock;
        Epoller _epoller;
        std::unordered_map<int, Connection *> _connections;
        struct epoll_event *_revs;
        int _num;
        func_t _service;
    };
}